package servlet;

import javabean.Cart;
import javabean.CartItem;
import javabean.Food;
import javabean.FoodCategory;
import service.AddCartService;
import service.AddCartServiceImpl;
import servlet.BaseServlet.BaseServlet;
import utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/addCartServlet")
public class AddCartServlet extends BaseServlet {

    private AddCartService addCartService = new AddCartServiceImpl();

    public void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Food> foods = addCartService.queryFoods();

        List<FoodCategory> foodCategorys = addCartService.queryFoodCategorys();

        req.setAttribute("foods",foods);

        req.setAttribute("foodCategorys",foodCategorys);

        req.getRequestDispatcher("/phone/unpackage/meun.jsp").forward(req,resp);

    }


    public void getFood(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"),0);

        Food food = addCartService.queryFoodById(id);

        req.setAttribute("food",food);

        req.getRequestDispatcher("/phone/unpackage/meun_item.jsp").forward(req,resp);
    }


    public void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取请求的参数，餐品编号
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        //调用service层根据id得到菜品信息
        Food food = addCartService.queryFoodById(id);
        //把餐品信息转化为CartItem购物车项
        CartItem cartItem = new CartItem(food.getId(),1,food.getName(),1,food.getCpp(),food.getCpp());
        //调用Cart.addItem()添加商品项
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if(cart == null){
            cart = new Cart();
            req.getSession().setAttribute("cart",cart);
        }
        cart.addItem(cartItem);

        System.out.println(cart);
        //重定向回菜单界面meun
        resp.sendRedirect(req.getContextPath() + "/addCartServlet?action=list");

    }

}
